import * as Y from "yjs";
import { WebsocketProvider } from "y-websocket";
import { MonacoBinding } from "y-monaco";
import * as monaco from "monaco-editor";

export const useYjs = () => {
  /* eslint-env browser */

  const ydoc = new Y.Doc();
  const provider = new WebsocketProvider(
    "wss://localhost:5467/ws", // use the public ws server
    // `ws${location.protocol.slice(4)}//${location.host}/ws`, // alternatively: use the local ws server (run `npm start` in root directory)
    "monaco-demo", // room name
    ydoc,
  );
    // set src
  const ytext = ydoc.getText("monaco");
  const monacoEditor = document.getElementById("monaco-editor")
  if (!monacoEditor) 
    throw new Error("No monaco editor found");
    
  const editor = monaco.editor.create(monacoEditor, {
    value: "",
    language: "typescript",
    theme: "vs-dark",
  });
  const monacoBinding = new MonacoBinding(
    ytext,
    editor.getModel()!,
    new Set([editor]),
    provider.awareness,
  );
  // another button
  const connectBtn = document.getElementById("y-connect-btn");
  if (!connectBtn) 
    throw new Error("No connect button found");
    
  connectBtn.addEventListener("click", () => {
    if (provider.shouldConnect) {
      provider.disconnect();
      connectBtn.textContent = "Connect";
    }
    else {
      provider.connect();
      connectBtn.textContent = "Disconnect";
    }
  });
  // what ?
  return { provider, ydoc, ytext, monacoBinding };
};
